#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
//回调函数
//新线程 
void *ThreadRun(void *arg)
{
  pthread_detach(pthread_self());
  char* msg = (char*)arg;
  int count = 0;
  while(count < 5)
  {
    //printf("I am %s, pid: %d , ppid: %d, id : %d\n", (char*)arg, getpid(), getppid(), pthread_self());
    printf("%s pid: %d, ppid: %d, tid: %lu\n", msg, getpid(), getppid(), pthread_self());
    sleep(1);
    count++;
  }

  pthread_exit((void*)121);// 线程退出
  //exit(0);
  //return (void*)101;
}

int main()
{ 
   pthread_t tid[5];
   for(int i = 0; i < 5; i++){
     //char buffer[64];
     char *buffer = (char*)malloc(64);
     sprintf(buffer, "thread %d", i);//将打印到显示器的内容 定位到buffer中
     //pthread_create(&tid[i], NULL, ThreadRun, (void*)"thread 1");
     pthread_create(&tid[i], NULL, ThreadRun, (void*)buffer);
     printf("%s tid is : %lu\n",buffer, tid[i]); 
   }
  
  // 取消线程
  // pthread_cancel(tid[0]);
  // pthread_cancel(tid[4]);
  
    //主线程 
   while(1){
    printf("I am main thread!, pid: %d , ppid %d, tid: %lu\n", getppid(), getppid(), pthread_self());
      sleep(2);
    }
   
   //主线程等待
 // for(int i =0; i<5; i++){
 //   void *ret = NULL;
 //   pthread_join(tid[i], &ret);
 //   printf("thread %d[%lu]... quit, quit code: %d\n", i, tid[i], (int)ret);
 // }
  return 0;
}
